package com.inspectortime.admin.emulate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import com.inspectortime.domain.User;
import com.inspectortime.repository.Repository;
import com.inspectortime.util.SpringValidatorUtils;

public class BecomeSomeoneController extends SimpleFormController {
	
	public void setRepository(Repository repository) {
		this.repository = repository;
	}

	private Repository repository;

	private static Log log = LogFactory.getLog(BecomeSomeoneController.class);

	protected Object formBackingObject(HttpServletRequest request) throws Exception {
		BecomeSomeoneForm form = new BecomeSomeoneForm();
		return form;
	}
	
	protected ModelAndView onSubmit(HttpServletRequest request,
			HttpServletResponse response, Object command, BindException errors)
			throws Exception {
				
		return new ModelAndView(this.getSuccessView());
	}
	
	/**
	 * Override empty parent method to log validation errors for debugging
	 * purposes only. Can be removed.
	 */
	protected void onBindAndValidate(HttpServletRequest request,
			Object command, BindException errors) throws Exception {
		SpringValidatorUtils.logValidationErrors(log, errors);
	}

	protected Map referenceData(HttpServletRequest request) throws Exception {
		Map<String, Object> data = new HashMap<String, Object>();
		List<User> users = repository.findAllUsers();
		List<String> emails = new ArrayList<String>();
		for (User user : users) {
			emails.add("" + user.getEmail() + "");
		}
		data.put("userEmails", emails);
		return data;
	}

}
